package com.zb.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
	private Connection con;
	private PreparedStatement pst;
	private ResultSet rs;
	
	public boolean getConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url="jdbc:mysql://localhost:3306/carhelp";
			con=DriverManager.getConnection(url, "root","ok");
			return true;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}
	public ResultSet query(String sql,Object...params){
		try {
			if(getConnection()){
				pst=con.prepareStatement(sql);
				for (int i = 0; i < params.length; i++) {
					pst.setObject(i+1,params[i]);
				}
				rs=pst.executeQuery();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
	public void update(String sql,Object...params){
		try {
			if(getConnection()){
				pst=con.prepareStatement(sql);
				for (int i = 0; i < params.length; i++) {
					pst.setObject(i+1,params[i]);
				}
				pst.executeUpdate();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void close(){
		try {
			if (rs != null) {
				rs.close();
			}
			if (pst != null) {
				pst.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
